import React, { useEffect } from 'react';
import {
    Form,
    Input,
    Row,
    Col,
    DatePicker,
    InputNumber,
    Tag,
    message,
} from "antd";
import assessmentList from "@/staticLists/assessmentList";
import { readData } from '@/staticLists/assessmentList';
import DropPopover from "@/components/DropPopover"
import { useSelector, useDispatch } from "umi"
import { formatDate } from "@/utils/format"
import { assessmentRule } from "@/utils/rules";
import moment from 'moment';
import $http from "@/services"
export default function index({ _initAssessList }) {
    const { assesDetail } = useSelector(state => state.assessment)
    const { user: { identity } } = useSelector(state => state.user)
    const [form] = Form.useForm();
    const dispatch = useDispatch();
    async function checkForm(item) {
        let oldValue = assesDetail[item.itemName];
        // 看是否为其搜索中传过来的若为则会传递id值过来
        const newValue = item._id ? item._id : form.getFieldValue(item.itemName);
        // 其try,catch无法捕捉到其规则错误
        const err = form.getFieldsError();
        const isError = err.some(el => el.errors.length > 0);
        if (isError) {
            form.setFieldsValue({ [item.itemName]: staffDetail[item.itemName] });
            return;
        }
        // 判断是否一致
        if (oldValue === newValue) return;
        updateAssessDetail(item.itemName, newValue);
    }

    // 更新level等级级别的
    const updateAssessDetail = async (type, updateVal) => {
        console.log(type, updateVal)
        const { data, msg } = await $http.updateAssessment({
            _id: assesDetail._id,
            type,
            updateVal
        })
        console.log(data, msg)
        if (data) return;
        message.success(msg);
        dispatch({
            type: "assessment/getDetailAsses",
            payload: assesDetail._id
        })
        _initAssessList();
    }


    //- 表单集合映射
    const groupData = {
        input: (item) => (
            <Input placeholder={item.initVal} onBlur={() => checkForm(item)} />
        ),
        inputNumber: (item) => (
            <InputNumber
                placeholder={item.initVal}
                readOnly={item.readOnly}
                onBlur={() => checkForm(item)}
            />
        ),
        popover: (item) => {
            return item.itemName === 'staffNameVal' ? (
                <Tag>{assesDetail.staffName.userName}</Tag>
            ) : (
                <Input
                    readOnly
                    className="border-color"
                    addonAfter={
                        <>
                            <DropPopover
                                placeValue={item.labelTxt}
                                interfaced={item.url}
                                searchType={item.type}
                                getnewValue={(obj) => {
                                    const setData = {
                                        [item.itemName]: obj[item.type],
                                        [item.itemName.split('V')[0]]: obj._id,
                                    };
                                    item.itemName === 'currentLevelVal' &&
                                        (setData.standardScore = obj.levelScore);
                                    form.setFieldsValue(setData);
                                    console.log(setData)
                                    updateAssessDetail("currentLevel", setData.currentLevelVal)
                                    // updateLevelInfo(
                                    //     { itemName: 'currentLevel' },
                                    //     { currentLevel: obj._id },
                                    // );
                                }}
                            />
                        </>
                    }
                />
            );
        },
        date: (item) => (
            <DatePicker
                placeholder="请选择入职时间"
                style={{ width: '100%' }}
                onBlur={() => checkForm(item)}
            />
        ),
        tag: (item) => (
            <Tag>
                {item.itemName === 'departmentName'
                    ? assesDetail.staffName?.department?.departmentName || '--'
                    : formatDate(assesDetail.staffName?.onboardingTime)}
            </Tag>
        ),
    };
    return (
        <Form
            layout='vertical'
            form={form}
            initialValues={{
                ...assesDetail,
                date: moment(assesDetail.date),
                currentLevelVal: assesDetail?.currentLevel?.levelName
            }
            }
        >
            {assessmentList.map((el, index) => {
                return (<Row justify={"space-between"} key={index}>
                    {el.map((item, childIndex) => {
                        return (<Col span={11} key={childIndex}>
                            <Form.Item
                                label={item.labelTxt}
                                name={item.itemName}
                                rules={assessmentRule[item.itemName]}
                            >
                                {groupData[item.renderType](item)}
                            </Form.Item>
                        </Col>)
                    })}
                </Row>)
            })}
            {identity == 1 && (readData.map((el, index) => {
                return (<Row justify={"space-between"} key={index}>
                    {el.map((item, childIndex) => {
                        return (<Col span={11} key={childIndex}>
                            <Form.Item
                                label={item.labelTxt}
                                name={item.itemName}
                                rules={assessmentRule[item.itemName]}
                            >
                                {groupData[item.renderType](item)}
                            </Form.Item>
                        </Col>)
                    })}
                </Row>)
            }))}
        </Form>

    )
}
